package info.niwota.web.proxy;

import x.org.apache.http.ProtocolVersion;
import x.org.apache.http.RequestLine;
import x.org.apache.http.message.BasicRequestLine;

public class ProxyRequestLine extends BasicRequestLine {

	private static final long serialVersionUID = 1L;

	public boolean absolute = false;
	public String host = null;
	public int port = -1;
	public String pathQuery;

	public ProxyRequestLine(RequestLine rl) {
		this(rl.getMethod(), rl.getUri(), rl.getProtocolVersion());
	}

	public ProxyRequestLine(String method, String uri,
			ProtocolVersion version) {
		super(method, uri, version);

		parse(uri);
	}

	@Override
	public String getUri() {
		return pathQuery;
	}

	public boolean isAbsolute() {
		return absolute;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	private void parse(String ruri) {
		int idx1 = ruri.indexOf("://");
		if (idx1 == -1) {
			return;
		}
		absolute = true;

		idx1 += 3;
		int idx2 = ruri.indexOf("/", idx1);
		final String hostport = (idx2 == -1 ? ruri.substring(idx1) : ruri
				.substring(idx1, idx2));

		pathQuery = (idx2 == -1 ? "/" : ruri.substring(idx2));
		host = hostport;
		String ports = null;
		String[] sa = hostport.split(":");
		if (sa.length > 1) {
			ports = sa[sa.length - 1];
			host = sa[sa.length - 2];
		}

		port = ports == null ? 80 : Integer.parseInt(ports);
	}

	@Override
	public String toString() {
		return "ProxyRequestLine [absolute=" + absolute + ", host=" + host
				+ ", port=" + port + ", pathQuery=" + pathQuery + "]";
	}

}
